package com.xyz.util;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONUtil;

public class ResponseUtil {

    // 不通过mvc直接返回json给前端
    public static void outWithJson(HttpServletResponse response, Object obj) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = response.getWriter()) {
            out.print(JSONUtil.toJsonStr(obj));
        } catch (IOException ignored) {
        }
    }

    public static void readFileResponse(HttpServletResponse response, File file, String fileName) {
        if (file.exists()) {
            try (
                    InputStream fis = Files.newInputStream(file.toPath());
            ) {
                response.reset();
                response.setContentType("application/octet-stream");
                String encode = URLEncoder.encode(fileName, "UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=\"" + encode + "\"");
                byte[] b = new byte[1024];
                int len;
                while ((len = fis.read(b)) > 0) {
                    response.getOutputStream().write(b, 0, len);
                }
            } catch (Exception ignored) {
            }
        }
    }

    public static HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            // String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(Files.newInputStream(Paths.get(path)));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (Exception ignored) {
        }
        return response;
    }

}
